package com.ggh.jinjilive.ui.map;

import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.blankj.utilcode.util.SizeUtils;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ActivityNearMapBinding;
import com.ggh.jinjilive.dialog.NearInformationDialog;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.GeneralUtils;
import com.gyf.immersionbar.ImmersionBar;

import java.util.HashMap;
import java.util.Map;

@Route(path = ARouterUtils.NearMapActivity)
public class NearMapActivity extends BaseActivity<ActivityNearMapBinding> implements View.OnClickListener, AMap.OnMapClickListener {
    private Bundle savedInstanceState;
    //经纬度
    private LatLonPoint mLatLonPoint;
    //弹框
    private NearInformationDialog nearInformationDialog;

    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private Marker marker;
    private GeocodeSearch geocoderSearch = new GeocodeSearch(mContext);
    //店铺
    private String shopLocation;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).init();
    }

    @Override
    public void initParam() {
        super.initParam();
        mLatLonPoint = getIntent().getParcelableExtra("latLonPoint");
        shopLocation = getIntent().getStringExtra("shopLocation");
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
        return R.layout.activity_near_map;

    }


    @Override
    public void initView() {
        super.initView();
        if(!TextUtils.isEmpty(shopLocation) && shopLocation.equals("店铺")){
            //确认
            binding.tvConfirm.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        super.initData();
        // 此方法必须重写
        binding.ScottMap.onCreate(savedInstanceState);
        //
        setWhiteActionBarStyle("选择位置",true,true);
        //获取状态栏高度
        binding.llSpacing.setPadding(0, SizeUtils.dp2px(25),0,0);
        //附近信息弹框
        nearInformationDialog = new NearInformationDialog(mContext);
        //地理编码与逆地理编码类。 地理编码又称地址匹配，指的是从已知的地址描述到对应的经纬 度坐标的转换，
        // 即根据地址信息，获取地址所对应的点坐标等。
        // 逆地理编码即地址解析服务，
        // 具体是指从已知的经纬度坐标到对 应的地址描述（如省市、街区、楼层、房间等）的转换。
        // 通过该类提供的方法可获取对应位置的地理描述，
        // 分为3种地物 类型：交叉路口、兴趣点、道路。
        geocoderSearch = new GeocodeSearch(mContext);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if(null != mLatLonPoint){
                    Map<String,Object> params = new HashMap<>();
                    params.put("lat",mLatLonPoint.getLatitude() +"");
                    params.put("lng",mLatLonPoint.getLongitude() +"");
                    params.put("province", regeocodeResult.getRegeocodeAddress().getProvince());
                    params.put("city", regeocodeResult.getRegeocodeAddress().getCity());
                    params.put("district", regeocodeResult.getRegeocodeAddress().getDistrict());
                    GeneralUtils.newUpdateMap(params);
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
        //地图
        aMap = binding.ScottMap.getMap();
        //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle = new MyLocationStyle();
        //隐藏定位点外圈圆的颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        //设置地图点击事件
        aMap.setOnMapClickListener(this);
        if(!TextUtils.isEmpty(shopLocation) && shopLocation.equals("店铺")){
            //只定位一次。
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
            //设置定位蓝点的Style
            aMap.setMyLocationStyle(myLocationStyle);
            // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
            aMap.setMyLocationEnabled(true);
            //按照传入的CameraUpdate参数改变地图状态。
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
            //设置用户定位信息监听接口。
            aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
                @Override
                public void onMyLocationChange(Location location) {
                    if(null == mLatLonPoint){
                        mLatLonPoint = new LatLonPoint(location.getLatitude(),location.getLongitude());
                    }
                    //查询附近信息
                    nearInformation("",location.getLatitude(),location.getLongitude());
                }
            });

        }else if(null == mLatLonPoint && userMobile.getIs_map() == 0){
            //只定位一次。
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
            //设置定位蓝点的Style
            aMap.setMyLocationStyle(myLocationStyle);
            // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
            aMap.setMyLocationEnabled(true);
            //按照传入的CameraUpdate参数改变地图状态。
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
            //设置用户定位信息监听接口。
            aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
                @Override
                public void onMyLocationChange(Location location) {
                    if(null == mLatLonPoint){
                        mLatLonPoint = new LatLonPoint(location.getLatitude(),location.getLongitude());
                    }
                    //查询附近信息
                    nearInformation("",location.getLatitude(),location.getLongitude());
                }
            });
        }
        if(null != mLatLonPoint){
            LatLng latLng = new LatLng(mLatLonPoint.getLatitude(),mLatLonPoint.getLongitude());
            if(null != marker){
                marker.remove();
            }
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            marker = aMap.addMarker(markerOptions);

            CameraPosition cameraPosition = new CameraPosition(new LatLng(mLatLonPoint.getLatitude(),mLatLonPoint.getLongitude()), 15, 0, 30);
            CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
            aMap.moveCamera(cameraUpdate);
        }else if(!TextUtils.isEmpty(userMobile.getLat())){
            double Latitude = Double.valueOf(userMobile.getLat());
            double Longitude = Double.valueOf(userMobile.getLng());
            //当前位置
            mLatLonPoint = new LatLonPoint(Latitude,Longitude);
            if(null != marker){
                marker.remove();
            }
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(new LatLng(Latitude,Longitude));
            marker = aMap.addMarker(markerOptions);
            CameraPosition cameraPosition = new CameraPosition(new LatLng(Latitude,Longitude), 15, 0, 30);
            CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
            aMap.moveCamera(cameraUpdate);
        }

    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //确认
        binding.tvConfirm.setOnClickListener(this);
        //软键盘搜索
        binding.etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String content = v.getText().toString();
                    nearInformation(content,0,0);
                    return true;
                }
                return false;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_confirm://确认
                Intent i = new Intent();
                i.putExtra("latLonPoint", mLatLonPoint);
                setResult(2011, i);
                finish();
                break;
        }
    }

    /**
     * 地图点击
     * @param latLng
     */
    @Override
    public void onMapClick(LatLng latLng) {
        mLatLonPoint = new LatLonPoint(latLng.latitude,latLng.longitude);
        if(null != marker){
            marker.remove();
        }
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        marker = aMap.addMarker(markerOptions);
        RegeocodeQuery query = new RegeocodeQuery(mLatLonPoint, 0, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
        nearInformation("",latLng.latitude,latLng.longitude);
    }

    private void nearInformation(String searchContent,double latitude,double longitude){
        PoiSearch.Query query = new PoiSearch.Query(searchContent,"");
        query.setPageSize(50);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(this, query);
        if(TextUtils.isEmpty(searchContent)){
            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude, longitude), 1000));//设置周边搜索的中心点以及半径
        }
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int rCode) {
                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (poiResult != null && poiResult.getPois().size() > 0) {
                        if(null != nearInformationDialog && !nearInformationDialog.isShowing()){
                            nearInformationDialog.show();
                            nearInformationDialog.setADD(poiResult.getPois());
                            nearInformationDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                                @Override
                                public void onSkipClicked(int position, Object mObject) {
                                    nearInformationDialog.dismiss();
                                    PoiItem poiItem = (PoiItem) mObject;
                                    if(null != poiItem){
                                        if(TextUtils.isEmpty(shopLocation)){
                                            //当前位置
                                            mLatLonPoint = poiItem.getLatLonPoint();
                                            LatLonPoint latLonPoint = poiItem.getLatLonPoint();
                                            LatLng latLng = new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude());
                                            if(null != marker){
                                                marker.remove();
                                            }
                                            MarkerOptions markerOptions = new MarkerOptions();
                                            markerOptions.position(latLng);
                                            marker = aMap.addMarker(markerOptions);

                                            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 0, GeocodeSearch.AMAP);
                                            geocoderSearch.getFromLocationAsyn(query);

                                            CameraPosition cameraPosition = new CameraPosition(new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude()), 15, 0, 30);
                                            CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                                            aMap.moveCamera(cameraUpdate);
                                        }else {
                                            Intent intent = new Intent();
                                            intent.putExtra("PoiItem", poiItem);
                                            setResult(2032, intent);
                                            finish();
                                        }
                                    }
                                }
                            });
                        }
                    }else {
                        Toast.makeText(mContext,"无搜索结果"+rCode,Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(mContext,"错误码"+rCode,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        binding.ScottMap.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        binding.ScottMap.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        binding.ScottMap.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        binding.ScottMap.onSaveInstanceState(outState);
    }

}
